package com.snack.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.snack.shop.entity.PickupCategory;
import com.snack.shop.mapper.PickupCategoryMapper;
import com.snack.shop.service.PickupCategoryService;
import com.snack.shop.common.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 代取分类服务实现
 */
@Service
@RequiredArgsConstructor
public class PickupCategoryServiceImpl implements PickupCategoryService {

    private final PickupCategoryMapper pickupCategoryMapper;

    @Override
    public List<PickupCategory> getEnabledList() {
        LambdaQueryWrapper<PickupCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PickupCategory::getStatus, 1)
                .orderByAsc(PickupCategory::getSort);
        return pickupCategoryMapper.selectList(wrapper);
    }

    @Override
    public PickupCategory getById(Long id) {
        return pickupCategoryMapper.selectById(id);
    }

    @Override
    public PickupCategory getByServiceType(Integer serviceType) {
        LambdaQueryWrapper<PickupCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PickupCategory::getServiceType, serviceType)
                .last("LIMIT 1");
        return pickupCategoryMapper.selectOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBasePriceByServiceType(Integer serviceType, BigDecimal basePrice) {
        PickupCategory category = getByServiceType(serviceType);
        if (category == null) {
            throw new BusinessException("代取分类不存在：serviceType=" + serviceType);
        }
        category.setBasePrice(basePrice);
        pickupCategoryMapper.updateById(category);
    }
}

